package pt.elvis.revanweb.client.uiBinders;

import pt.elvis.revanweb.client.ImageAnchor;
import pt.elvis.revanweb.client.RevanWeb;
import pt.elvis.revanweb.client.DatabaseObjects.Bookmarks_Objects;
import pt.elvis.revanweb.client.DatabaseObjects.DatabaseHelper;
import pt.elvis.revanweb.client.DatabaseObjects.MyRequestCallback;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Widget;

/**
 * It's where the bookmarks are show. It loads the bookmarks from the
 * database through a PHP RPC, fills the static list on
 * RevanWeb.bookmarksListof object type Bookmarks_Objects, creates a
 * ImageAnchor object and sends to a FlexTable. It onlys shows the first
 * 25 bookmarks.
 * @author <b>Elvis Pestana</b>
 * @return Returns a FlowPanel wrapped in a HTMLPanel.
 * 
 * @see ImageAnchor
 * @see Bookmarks_Objects
 * @see FlowPanel
 * @see FlexTable
 * @see HTMLPanel
 **/

public class BookmarksPanel extends Composite {
	private String SESSION_ID = null;
	private FlexTable flex = new FlexTable();
	
	private static BookmarksPanelUiBinder uiBinder = GWT
			.create(BookmarksPanelUiBinder.class);

	interface BookmarksPanelUiBinder extends UiBinder<Widget, BookmarksPanel> {
	}
	
	public BookmarksPanel(String SESSION_ID) {
		this.SESSION_ID = SESSION_ID;
		getBookmarksFromDatabase();
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField
	FlowPanel flowPanel;
	
	private void getBookmarksFromDatabase() {
		String variavel = "sessionid=" + SESSION_ID;
		DatabaseHelper.getData_POST("getBookmarkList.php", variavel,
				new MyRequestCallback() {

					@Override
					protected void onText(String text) {
						if (!text.equals("NoUserFound")) {							
							parseBoomarks(text);
							RevanWeb.isLoaded = true;
							addToFlowPanel();
						}							
						else							
							Window.alert("Something is wrong: private void getBookmarksFromDatabase()\n" + text);
					}
				});
	}

	// This builds the bookmarks panel that appears.
	public void rebuildBookmarksPanel() {
		flex.clear();
		flex.removeAllRows();
		addToFlowPanel();
	}
	
	private void addToFlowPanel() {
		int column = 0;
		int numRows = flex.getRowCount();		
		int maxBookmarks = 0;
		for (final Bookmarks_Objects val : RevanWeb.bookmarksList) {
			if (maxBookmarks < 25) {
				if (val.getActive()) {
					String ran = "?" + Random.nextInt(10000);
					final ImageAnchor imageAnchor = new ImageAnchor(
							val.getBookmarkImagePath() + ran, "|"
									+ val.getBookmarkCount() + "| "
									+ val.getBookmarkName(),
							val.getIdBookmark(), val.getBookmarkDescription());
					imageAnchor.setHref(val.getBookmarkURL());
					final String variavel = "idBookmark=" + val.getIdBookmark()
							+ "&sessionid=" + SESSION_ID;
					imageAnchor.addClickHandler(new ClickHandler() {

						@Override
						public void onClick(ClickEvent event) {
							DatabaseHelper.getData_POST(
									"updateBookmarkCount.php", variavel,
									new MyRequestCallback() {

										@Override
										protected void onText(String text) {
											String value = jsonParse(text);
											if (value.equals("true")) {
												val.setBookmarkCount(val
														.getBookmarkCount() + 1);
												imageAnchor.setImageCaption("|"
														+ val.getBookmarkCount()
														+ "| "
														+ val.getBookmarkDescription());
											} else if (value.equals("false"))
												Window.alert("Something is wrong: private void addToFlowPanel()\n" + text);
											else
												Window.alert("Something is wrong: private void addToFlowPanel()\n" + text);
										}

										private String jsonParse(String text) {
											JSONValue value = JSONParser
													.parseStrict(text);
											JSONObject jsonObject = value
													.isObject();
											return jsonObject.get("Success")
													.isString().stringValue();
										}
									});
						}
					});
					if (column < 5) {
						flex.setWidget(numRows, column, imageAnchor);
						flex.getCellFormatter().setAlignment(numRows, column,
								HasHorizontalAlignment.ALIGN_CENTER,
								HasVerticalAlignment.ALIGN_MIDDLE);
						flex.getCellFormatter().setStyleName(numRows, column,
								"imgteaser");
						RevanWeb.imageAnchorList.add(imageAnchor);
						column++;
					} else {
						column = 0;
						numRows = flex.getRowCount();
						flex.setWidget(numRows, column, imageAnchor);
						flex.getCellFormatter().setAlignment(numRows, column,
								HasHorizontalAlignment.ALIGN_CENTER,
								HasVerticalAlignment.ALIGN_MIDDLE);
						flex.getCellFormatter().setStyleName(numRows, column,
								"imgteaser");
						RevanWeb.imageAnchorList.add(imageAnchor);
						column++;
					}					
					maxBookmarks++;
				}
			} else {
				break;
			}
		}
		flowPanel.add(flex);
	}

	//Parser for the data received
	private void parseBoomarks(String jsonData) {
		JSONValue value = JSONParser.parseStrict(jsonData);

		JSONObject bookmarksObj = value.isObject();

		JSONArray bookmarksArray = bookmarksObj.get("bookmarks").isArray();

		if (bookmarksArray != null) {

			for (int i = 0; i < bookmarksArray.size(); i++) {

				JSONObject bookmarkObj = bookmarksArray.get(i).isObject();

				String tmp = null;
				int idBookmark = Integer.parseInt(bookmarkObj.get("idBookmark")
						.isString().stringValue());
				String bookmarkName = bookmarkObj.get("bookmarkName")
						.isString().stringValue();
				String bookmarkURL = bookmarkObj.get("bookmarkURL").isString()
						.stringValue();
				String bookmarkDescription = null;
				try {
					tmp = bookmarkObj.get("bookmarkDescription").isString().stringValue();
				} catch (Exception e) {					
					Window.alert(e.getMessage());
				}
				if (!tmp.equals("null"))
					bookmarkDescription = tmp;
				String bookmarkImagePath = null;
				tmp = bookmarkObj.get("bookmarkImagePath").isString()
						.stringValue();
				if (!tmp.equals("null"))
					bookmarkImagePath = tmp;
				tmp = bookmarkObj.get("active").isString().stringValue();
				boolean active = false;
				if (tmp.equals("1"))
					active = true;
				int bookmarkCount = Integer.parseInt(bookmarkObj
						.get("bookmarkCount").isString().stringValue());

				RevanWeb.bookmarksList.add(new Bookmarks_Objects(idBookmark,
						bookmarkName, bookmarkURL, bookmarkDescription,
						bookmarkImagePath, active, bookmarkCount));
			}
		}
	}

}
